<template>
  <div class="order-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">我的订单</h2>
      <p class="page-subtitle">查看和管理您的订单信息</p>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <div class="search-container">
        <div class="search-row">
          <el-input
            v-model="searchOrderID"
            placeholder="搜索订单号"
            prefix-icon="Search"
            clearable
            class="search-input"
          />
          <el-input
            v-model="searchOrderDate"
            placeholder="搜索订单日期"
            prefix-icon="Calendar"
            clearable
            class="search-input"
          />
          <el-select
            v-model="searchOrderStatus"
            placeholder="订单状态"
            clearable
            class="search-input"
          >
            <el-option label="已提交" value="已提交" />
            <el-option label="配送中" value="配送中" />
            <el-option label="已送达" value="已送达" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </div>
        <div class="search-row">
          <el-input
            v-model="searchAddress"
            placeholder="搜索地址"
            prefix-icon="Location"
            clearable
            class="search-input"
          />
          <el-input
            v-model="searchContact"
            placeholder="搜索联系方式"
            prefix-icon="Phone"
            clearable
            class="search-input"
          />
        </div>
      </div>
    </el-card>

    <!-- 订单列表 -->
    <div class="orders-container">
      <div v-if="filteredOrders.length === 0" class="empty-state">
        <el-empty description="暂无订单数据">
          <el-button type="primary" @click="$router.push('/home/rest')">
            去下单
          </el-button>
        </el-empty>
      </div>

      <el-card
        v-for="(order, index) in filteredOrders"
        :key="index"
        class="order-card"
        shadow="hover"
      >
        <!-- 订单头部 -->
        <div class="order-header">
          <div class="order-info">
            <div class="order-number">
              <el-icon><Document /></el-icon>
              <span>订单号：{{ order.OrderID }}</span>
            </div>
            <div class="order-date">
              {{ new Date(order.OrderDate).toLocaleDateString() }}
            </div>
          </div>
          <div class="order-status">
            <el-tag
              :type="getStatusType(order.OrderStatus)"
              :effect="order.OrderStatus === '已完成' ? 'plain' : 'dark'"
              size="large"
            >
              {{ order.OrderStatus }}
            </el-tag>
          </div>
        </div>

        <!-- 订单内容 -->
        <div class="order-content">
          <!-- 订单基本信息 -->
          <div class="order-basic-info">
            <div class="info-section">
              <div class="info-item">
                <el-icon class="info-icon"><User /></el-icon>
                <span class="info-label">顾客：</span>
                <span class="info-value">{{ order.username }}</span>
              </div>
              <div class="info-item">
                <el-icon class="info-icon"><Location /></el-icon>
                <span class="info-label">地址：</span>
                <span class="info-value">{{ order.address }}</span>
              </div>
              <div class="info-item">
                <el-icon class="info-icon"><Phone /></el-icon>
                <span class="info-label">联系方式：</span>
                <span class="info-value">{{ hideContactInfo(order.contact) }}</span>
              </div>
              <div class="info-item" v-if="order.beizhu">
                <el-icon class="info-icon"><ChatDotRound /></el-icon>
                <span class="info-label">备注：</span>
                <span class="info-value">{{ order.beizhu }}</span>
              </div>
            </div>

            <div class="price-section">
              <div class="total-price">
                <span class="price-label">总金额</span>
                <span class="price-value">¥{{ order.TotalPrice }}</span>
              </div>
            </div>
          </div>

          <!-- 订单详情 -->
          <div class="order-details">
            <div class="details-header">
              <h4>订单详情</h4>
            </div>
            <div class="details-list">
              <div
                v-for="(detail, detailIndex) in getOrderDetails(order.OrderID)"
                :key="detailIndex"
                class="detail-item"
              >
                <div class="detail-image">
                  <img :src="detail.ImageURL" alt="菜品图片" />
                </div>
                <div class="detail-info">
                  <div class="dish-name">{{ detail.DishName }}</div>
                  <div class="dish-meta">
                    <span class="dish-price">¥{{ detail.Price }}</span>
                    <span class="dish-count">x{{ detail.Count }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="order-actions">
            <el-button
              v-if="order.OrderStatus === '已送达'"
              type="success"
              @click="confirmReceived(order.OrderID)"
            >
              确认收到
            </el-button>
            <el-button
              v-else-if="order.OrderStatus !== '已取消' && order.OrderStatus !== '已完成'"
              type="danger"
              @click="cancelOrder(order.OrderID)"
            >
              取消订单
            </el-button>
            <el-button
              v-if="order.OrderStatus === '已取消'"
              type="primary"
              @click="restoreOrder(order)"
            >
              恢复订单
            </el-button>
            <el-button
              v-if="order.OrderStatus === '已完成'"
              type="danger"
              plain
              @click="deleteOrder(order)"
            >
              删除订单
            </el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { getOrdersApi1, cancelOrderApi } from "@/utils/api";
import {
  Document,
  User,
  Location,
  Phone,
  ChatDotRound,
  Search,
  Calendar
} from '@element-plus/icons-vue';

const orders = ref([]);
const orderDetails = ref([]);
const searchOrderID = ref("");
const searchOrderDate = ref("");
const searchAddress = ref("");
const searchOrderStatus = ref("");
const searchContact = ref("");

// 初始化订单列表
const init = async () => {
  const data = localStorage.getItem("user");
  const { user_id } = JSON.parse(data);
  const res = await getOrdersApi1({ user_id });
  if (res.code === 200) {
    orders.value = res.orders[0];
    orderDetails.value = res.orders[1];
    orders.value.sort((a, b) => b.OrderID - a.OrderID);
  }
};

// 计算过滤后的订单列表
const filteredOrders = computed(() => {
  return orders.value.filter((order) => {
    if (!order) return false;
    return (
      order.OrderID.toString().includes(searchOrderID.value) &&
      order.OrderDate &&
      new Date(order.OrderDate)
        .toLocaleDateString()
        .includes(searchOrderDate.value) &&
      order.address && 
      order.address.toLowerCase().includes(searchAddress.value.toLowerCase()) &&
      order.OrderStatus &&
      order.OrderStatus.toLowerCase().includes(
        searchOrderStatus.value.toLowerCase()
      ) &&
      order.contact &&
      order.contact.toLowerCase().includes(searchContact.value.toLowerCase()) &&
      order.OrderStatus !== "删除订单"
    );
  });
});

// 取消订单
const cancelOrder = async (id) => {
  const order = orders.value.find((item) => item.OrderID === id);
  // 如果订单状态: 已完成，则不允许取消
  if (order.OrderStatus === "已完成") {
    alert("已完成的订单不可取消");
    return;
  }

  if (order.OrderStatus !== "已完成") {
    const confirmMsg = "确认取消该订单?";
    if (confirm(confirmMsg)) {
      order.OrderStatus = "已取消";
      await updateOrderStatus(id, "已取消");
    }
  } else {
    alert("已完成的订单不可取消");
  }
};

// 恢复订单
const restoreOrder = async (order) => {
  const confirmMsg = "确认恢复该订单?";
  if (confirm(confirmMsg)) {
    order.OrderStatus = "已提交";
    await updateOrderStatus(order.OrderID, "已提交");
  }
};

// 确认收到订单
const confirmReceived = async (id) => {
  const confirmMsg = "确认收到该订单?";
  if (confirm(confirmMsg)) {
    const order = orders.value.find((item) => item.OrderID === id);
    order.OrderStatus = "已送达";
    await updateOrderStatus(id, "已完成");
    // 跟新订单列表
    await init();
  }
};

// 更新订单状态
const updateOrderStatus = async (id, status) => {
  const res = await cancelOrderApi({ id, orderStatus: status });
  await init();
};

// 删除订单
const deleteOrder = async (order) => {
  const confirmMsg = "确认删除该订单?";
  if (confirm(confirmMsg)) {
    const res = await cancelOrderApi({
      id: order.OrderID,
      orderStatus: "删除订单",
    });
    await init();
  }
};

// 部分隐藏联系方式的函数
const hideContactInfo = (contact) => {
  // 如果联系方式不为空并且长度大于等于11（例如手机号码），则隐藏中间四位数字
  if (contact && contact.length >= 11) {
    const hiddenDigits = "****";
    return contact.slice(0, 3) + hiddenDigits + contact.slice(-4);
  } else {
    return contact; // 如果长度不符合要求，则原样返回
  }
};

// 获取订单状态对应的标签类型
const getStatusType = (status) => {
  const statusMap = {
    '已提交': 'info',
    '配送中': 'warning',
    '已送达': 'success',
    '已完成': 'success',
    '已取消': 'danger'
  };
  return statusMap[status] || 'info';
};

// 根据订单ID获取订单详情
const getOrderDetails = (orderId) => {
  return orderDetails.value.filter(detail => detail.OrderID === orderId);
};

// 初始化订单列表
init();
</script>

<style lang="less" scoped>
.order-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 24px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;
  }

  .page-subtitle {
    color: #909399;
    margin: 0;
    font-size: 14px;
  }
}

.search-card {
  margin-bottom: 20px;
  border: none;

  :deep(.el-card__body) {
    padding: 20px;
  }
}

.search-container {
  .search-row {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }

    .search-input {
      flex: 1;
      max-width: 300px;
    }
  }
}

.orders-container {
  .empty-state {
    text-align: center;
    padding: 60px 20px;
    background: white;
    border-radius: 8px;
  }
}

.order-card {
  margin-bottom: 20px;
  border: none;
  border-radius: 12px;
  overflow: hidden;

  :deep(.el-card__body) {
    padding: 0;
  }
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: #fafbfc;
  border-bottom: 1px solid #ebeef5;

  .order-info {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .order-number {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      font-weight: 600;
      color: #303133;

      .el-icon {
        color: #409eff;
      }
    }

    .order-date {
      font-size: 14px;
      color: #909399;
    }
  }

  .order-status {
    .el-tag {
      font-size: 14px;
      padding: 8px 16px;
      border-radius: 20px;
    }
  }
}

.order-content {
  padding: 24px;
}

.order-basic-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f2f5;
}

.info-section {
  flex: 1;

  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    &:last-child {
      margin-bottom: 0;
    }

    .info-icon {
      color: #909399;
      margin-right: 8px;
      font-size: 16px;
    }

    .info-label {
      color: #606266;
      font-size: 14px;
      margin-right: 8px;
      min-width: 70px;
    }

    .info-value {
      color: #303133;
      font-size: 14px;
      flex: 1;
    }
  }
}

.price-section {
  text-align: right;

  .total-price {
    display: flex;
    flex-direction: column;
    align-items: flex-end;

    .price-label {
      font-size: 14px;
      color: #909399;
      margin-bottom: 4px;
    }

    .price-value {
      font-size: 24px;
      font-weight: 600;
      color: #f56c6c;
    }
  }
}

.order-details {
  margin-bottom: 24px;

  .details-header {
    margin-bottom: 16px;

    h4 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }

  .details-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .detail-item {
    display: flex;
    align-items: center;
    padding: 16px;
    background: #fafbfc;
    border-radius: 8px;
    border: 1px solid #f0f2f5;

    .detail-image {
      width: 80px;
      height: 80px;
      border-radius: 8px;
      overflow: hidden;
      margin-right: 16px;
      flex-shrink: 0;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .detail-info {
      flex: 1;

      .dish-name {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
        margin-bottom: 8px;
      }

      .dish-meta {
        display: flex;
        align-items: center;
        gap: 16px;

        .dish-price {
          font-size: 16px;
          font-weight: 600;
          color: #f56c6c;
        }

        .dish-count {
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }
}

.order-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  padding-top: 20px;
  border-top: 1px solid #f0f2f5;
}

// 响应式设计
@media (max-width: 768px) {
  .order-page {
    padding: 16px;
  }

  .search-container {
    .search-row {
      flex-direction: column;
      gap: 12px;

      .search-input {
        max-width: none;
      }
    }
  }

  .order-header {
    padding: 16px;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .order-content {
    padding: 16px;
  }

  .order-basic-info {
    flex-direction: column;
    gap: 16px;
  }

  .price-section {
    text-align: left;

    .total-price {
      align-items: flex-start;
    }
  }

  .detail-item {
    flex-direction: column;
    text-align: center;

    .detail-image {
      margin-right: 0;
      margin-bottom: 12px;
    }
  }

  .order-actions {
    flex-direction: column;

    .el-button {
      width: 100%;
    }
  }
}
</style>
